<!doctype html>
<html>
	<head>
		<meta name="viewport" content="width=device-width"/>
		<meta charset="utf-8"></meta>
		<link rel="stylesheet" href="bootstrap.min.css"></link>
		<link rel="stylesheet" href="cropper.min.css"></link>
		<link rel="stylesheet" href="avatar.css"></link>
		<title>更改头像</title>
	</head>
	<body>
		<div class="panel container">
			<div class="row">
				<div class="col-sm-12 col-md-9">
					<div class="preview" id="preview">
						<div class="preview-bg"></div>
					</div>
				</div>
				<div class="col-sm-12 col-md-3">
					<div class="action">
						<div class="row">
							<div class="mt-2 d-block d-md-none col-12"></div>
							<div class="col-6 col-md-12">
								<button class="btn btn-primary btn-100" id="selectImg">选择图片</button>
							</div>
							<div class="d-none d-md-block col-12" style="margin-top: 163px"></div>
							<div class="col-6 col-md-12">
								<button class="btn btn-success btn-100" id="submit">提交</button>
							</div>
						</div>
					</div>
				</div>
				<form id="hiddenForm">
					<input type="file" name="avatar" id="avatarFile" accept="image/jpeg,image/png,image/gif"></input>
				</form>
			</div>
		</div>
		<script src="jquery-3.4.1.min.js"></script>
		<script src="cropper.min.js"></script>
		<script src="message.js"></script>
		<script>
		var xml;
		function parseQuery(query){
			if(query[0] === '?'){
				query = query.substr(1);
			}
			var data = {};
			var params = query.split('&');
			params.forEach(function(one){
				var t = one.split('=');
				if(t.length === 1){
					data[decodeURIComponent(t[0])] = null;
				} else if(t.length === 2){
					data[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
				}
			});
			return data;
		}
		
		function buildQuery(data){
			var params = [];
			for(var key in data){
				params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
			}
			return params.join('&');
		}
		
		$('#selectImg').click(function(){
			$('#avatarFile').click();
		});
		//当文件被修改
		$('#avatarFile').change(function(){
			var files = $(this)[0].files;
			if(files.length > 0){
				$('#submit').show();
				$('#selectImg').text('更换图片');
				message('info', '提示', '请选择要使用的部分', 2000);
				var dataUrl = URL.createObjectURL(files[0]);
				var img = $('#preview').html('<img></img>').find('img:first');
				img.attr('src', dataUrl);
				img.cropper({
					viewMode: 1,
					aspectRatio: 1,
					ready: function(){
						URL.revokeObjectURL(dataUrl);
					},
				});
			}
		});
		//点击提交
		$('#submit').click(function(){
			var cropData = $('#preview img:first').cropper('getData');
			var formData = new FormData();
			var ucData = parseQuery(location.search);
			formData.append('avatar', $('#avatarFile')[0].files[0]);
			var url = ucData.ucapi + '/index.php?' + buildQuery({
				m: 'user',
				a: 'setavatar',
				x: parseInt(cropData.x),
				y: parseInt(cropData.y),
				size: parseInt(cropData.width),
				appid: ucData.appid,
				input: ucData.input,
				agent: ucData.agent,
				avatartype: ucData.avatartype,
			});
			//开始进行提交
			var btn = $('#submit');
			$.ajax({
				url: url,
				type: 'post',
				data: formData,
				contentType: false,
				processData: false,
				dataType: 'xml',
				beforeSend: function(){
					btn.attr('disabled', 'disabled');
					btn.text('正在上传 0%');
				},
				xhr: function() {
					var xhr = new XMLHttpRequest();
					xhr.upload.addEventListener('progress', function(e){
						btn.text('正在上传 ' + ((e.loaded / e.total) * 100).toString() + '%');;
					});
					return xhr;
				},
				success: function(res){
					btn.removeAttr('disabled', 'disabled');
					btn.text('提交');
					dom = $(res);
					xml = dom;
					if(dom.find('root message[type="error"]').length > 0){ //出错的情况
						var value = parseInt(dom.find('root message[type="error"]').attr('value'));
						switch(value){
							case -1:
								message('error', '提示', '页面已过期，请刷新重试');
								break;
							case '-2':
								message('error', '提示', '没有收到头像文件');
								break;
						}
					} else if(dom.find('root face').length > 0){ //头像上传成功的情况
						var success = parseInt(dom.find('root face').attr('success'));
						console.log(success);
						if(success === 1){
							message('success', '完成', '头像上传成功，请刷新页面查看新头像');
							btn.hide();
							$('#preview img:first').cropper('destroy').remove();
							$('#selectImg').text('选择图片');
						} else {
							message('warning', '提示', '头像上传失败：无法处理这张图片');
						}
					}
				},
				error: function(...args){
					btn.removeAttr('disabled', 'disabled');
					btn.text('提交');
					console.log(args);
				},
			});
		});
		</script>
	</body>
</html>